package com.minivision.sdktestdemo.ui.custom;

import android.content.Context;

import com.minivision.sdktestdemo.R;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2016/8/4.
 */
public class NetLrcLoader implements LrcLoader {
    private Retrofit mRetrofit;
    private LrcService mLrcService;
    private String mApiKey;
    private volatile String  mMusicName;
    private String mMusicHash;
    private int mMusicDuration;
    private String mErrorMsg;

    public NetLrcLoader(Context context, String baseUrl) {
        this(context, new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(baseUrl).build());
    }

    public NetLrcLoader(Context context, Retrofit retrofit) {
        mRetrofit = retrofit;
        mLrcService = mRetrofit.create(LrcService.class);
        mApiKey = context.getResources().getString(R.string.api_key);
    }

    @Override
    public String getLrcText(String name) {
        mMusicName = name;
        if (getMusicInfo(name)) {
            return getLrcContent(mMusicName, mMusicHash, mMusicDuration);
        } else {
            return "";
        }
    }

    String getLrcContent(String name, String hash, int duration) {
        Call<LrcResponse> responseCall = mLrcService.getLrc(mApiKey, name, hash, duration);
        try {
            Response<LrcResponse> response = responseCall.execute();
            if (response.isSuccessful()) {
                if (mMusicName.equals(name) && response.body().getData() != null) {
                    return response.body().getData().getContent();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        mErrorMsg = "没有找到相关歌曲的歌词";
        return "";
    }

    @Override
    public String getErrorMsg() {
        return mErrorMsg;
    }

    boolean getMusicInfo(String name) {
        Call<MusicResponse> mMusicCall = mLrcService.getMusicInfo(mApiKey, name, 1, 1);
        try {
            Response<MusicResponse> response = mMusicCall.execute();
            if (response.isSuccessful()) {
                MusicResponse.DataBeanResponse data = response.body().getData();
                if (mMusicName.equals(name) && data != null && data.getData() != null && data.getData().size() > 0) {
                    mMusicDuration = data.getData().get(0).getDuration();
                    mMusicHash = data.getData().get(0).getHash();
                    return true;
                }
                mErrorMsg = "没有找到相关歌曲的歌词";
            }
        } catch (IOException e) {
            e.printStackTrace();
            mErrorMsg = "获取歌词超时,请稍后";
        }
        return false;
    }

    @Override
    public LrcLoader setLrcLoader(LrcLoader loader) {
        return this;
    }
}
